'use client';

import 'dayjs/locale/en';
import 'dayjs/locale/zh';
import Script from 'next/script';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import relativeTime from 'dayjs/plugin/relativeTime';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { type ReactNode, useState } from 'react';
import type Bootstrap from 'bootstrap';
import { AppContext } from '@/contexts/app';
import ToastWrapper from '@/app/[locale]/toast/wrapper';
import OffcanvasWrapper from '@/app/[locale]/offcanvas/wrapper';
import ModalWrapper from '@/app/[locale]/modal/wrapper';
import { useLocale } from 'use-intl';
import type { TMetadata } from '@/types';
import Analysis from '@/app/[locale]/common/analysis/analysis';
import { nonEmpty, nonNull } from '@/lib/tool';

dayjs.extend(duration);
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(relativeTime);

export default function Wrapper({
  metadata,
  children,
}: {
  metadata: TMetadata;
  children: ReactNode;
}) {
  dayjs.locale(useLocale());
  const [isInitBootstrap, setIsInitBootstrap] = useState(false);
  const [bootstrap, setBootstrap] = useState<typeof Bootstrap>();
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            retry: false,
            queryKeyHashFn: (queryKey) =>
              JSON.stringify(
                queryKey
                  .filter(nonNull)
                  .filter(nonEmpty)
                  .filter((value: any) => {
                    if (typeof value !== 'object') {
                      return true;
                    }

                    const obj: Record<string, any> = {};
                    for (const key in value) {
                      if (nonNull(value[key])) {
                        obj[key] = value[key];
                      }
                    }
                    return Object.keys(obj).length > 0;
                  }),
              ),
          },
        },
      }),
  );

  function onReadyBootstrap() {
    setBootstrap(window.bootstrap);
    setIsInitBootstrap(true);
  }

  return (
    <>
      <QueryClientProvider client={queryClient}>
        <AppContext.Provider value={{ bootstrap, metadata }}>
          <ToastWrapper>
            <ModalWrapper>
              <OffcanvasWrapper>
                <>
                  {children}
                  <Analysis />
                </>
              </OffcanvasWrapper>
            </ModalWrapper>
          </ToastWrapper>
        </AppContext.Provider>
        <ReactQueryDevtools initialIsOpen={false} />
      </QueryClientProvider>

      <Script onReady={onReadyBootstrap} src="/lib/bootstrap.bundle.min.js" />
      {isInitBootstrap && <Script src="/lib/popover.min.js" />}
    </>
  );
}
